// 客户端认证工具
'use client';

import { useState, useEffect } from 'react';

// 用户类型
export interface User {
  id: number;
  username: string;
  email?: string;
  displayName: string;
  avatarUrl?: string;
  role: 'student' | 'teacher' | 'admin';
  createdAt: Date;
  lastLoginAt?: Date;
  profile?: {
    grade: number;
    school?: string;
    bio?: string;
  };
}

// API响应类型
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
}

// 注册参数
export interface RegisterParams {
  username: string;
  password: string;
  email?: string;
  school?: string;
  gradeLevel?: number;
}

// 登录参数
export interface LoginParams {
  username: string;
  password: string;
}

// 注册
export async function register(params: RegisterParams): Promise<ApiResponse<{ user: User; token: string }>> {
  try {
    const response = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

    const data = await response.json();

    // 如果成功，保存到本地存储
    if (data.success && typeof window !== 'undefined') {
      localStorage.setItem('user', JSON.stringify(data.data.user));
      localStorage.setItem('auth_token', data.data.token);
    }

    return data;
  } catch (error) {
    console.error('注册错误:', error);
    return {
      success: false,
      error: '网络错误，请稍后重试',
    };
  }
}

// 登录
export async function login(params: LoginParams): Promise<ApiResponse<{ user: User; token: string }>> {
  try {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

    const data = await response.json();

    // 如果成功，保存到本地存储
    if (data.success && typeof window !== 'undefined') {
      localStorage.setItem('user', JSON.stringify(data.data.user));
      localStorage.setItem('auth_token', data.data.token);
    }

    return data;
  } catch (error) {
    console.error('登录错误:', error);
    return {
      success: false,
      error: '网络错误，请稍后重试',
    };
  }
}

// 登出
export async function logout(): Promise<ApiResponse<null>> {
  try {
    const response = await fetch('/api/auth/logout', {
      method: 'POST',
    });

    const data = await response.json();
    
    // 清除本地存储
    if (typeof window !== 'undefined') {
      localStorage.removeItem('user');
      localStorage.removeItem('auth_token');
    }

    return data;
  } catch (error) {
    console.error('登出错误:', error);

    // 即使API调用失败，也清除本地存储
    if (typeof window !== 'undefined') {
      localStorage.removeItem('user');
      localStorage.removeItem('auth_token');
    }

    return {
      success: false,
      error: '网络错误，请稍后重试',
    };
  }
}

// 获取当前用户
export async function getCurrentUser(): Promise<ApiResponse<User>> {
  try {
    // 从localStorage获取Token
    const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;

    if (!token) {
      return {
        success: false,
        error: '未登录',
      };
    }

    const response = await fetch('/api/auth/me', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
      },
      credentials: 'include',
    });

    const data = await response.json();

    // 如果成功，保存到本地存储
    if (data.success && typeof window !== 'undefined') {
      localStorage.setItem('user', JSON.stringify(data.data));
    }

    return data;
  } catch (error) {
    console.error('获取用户信息错误:', error);
    return {
      success: false,
      error: '网络错误，请稍后重试',
    };
  }
}

// 从本地存储获取用户
export function getUserFromStorage(): User | null {
  if (typeof window === 'undefined') return null;
  
  try {
    const userStr = localStorage.getItem('user');
    if (!userStr) return null;
    
    return JSON.parse(userStr);
  } catch (error) {
    return null;
  }
}

// 清除本地用户信息
export function clearUserStorage() {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('user');
    localStorage.removeItem('auth_token');
  }
}

// 使用认证Hook
export function useAuth() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 加载用户信息
  useEffect(() => {
    loadUser();
  }, []);

  async function loadUser() {
    setLoading(true);
    setError(null);

    // 先从本地存储获取
    const cachedUser = getUserFromStorage();
    if (cachedUser) {
      setUser(cachedUser);
    }

    // 然后从服务器验证
    const response = await getCurrentUser();
    if (response.success && response.data) {
      setUser(response.data);
    } else {
      setUser(null);
      clearUserStorage();
      if (response.error) {
        setError(response.error);
      }
    }

    setLoading(false);
  }

  async function handleLogin(params: LoginParams) {
    setLoading(true);
    setError(null);

    const response = await login(params);
    if (response.success && response.data) {
      setUser(response.data.user);
      if (typeof window !== 'undefined') {
        localStorage.setItem('user', JSON.stringify(response.data.user));
      }
    } else {
      setError(response.error || '登录失败');
    }

    setLoading(false);
    return response;
  }

  async function handleRegister(params: RegisterParams) {
    setLoading(true);
    setError(null);

    const response = await register(params);
    if (response.success && response.data) {
      setUser(response.data.user);
      if (typeof window !== 'undefined') {
        localStorage.setItem('user', JSON.stringify(response.data.user));
      }
    } else {
      setError(response.error || '注册失败');
    }

    setLoading(false);
    return response;
  }

  async function handleLogout() {
    setLoading(true);
    setError(null);

    const response = await logout();
    setUser(null);
    clearUserStorage();

    setLoading(false);
    return response;
  }

  return {
    user,
    loading,
    error,
    login: handleLogin,
    register: handleRegister,
    logout: handleLogout,
    reload: loadUser,
  };
}

export default {
  register,
  login,
  logout,
  getCurrentUser,
  getUserFromStorage,
  clearUserStorage,
  useAuth,
};
